package com.FH.organization.emailRevice;

import com.FH.organization.emailSend.emailsendPullDTO;
import com.FH.util.AccessDB;
import com.FH.util.FileProcess;
import com.FH.util.ResultDTO;
import com.FH.util.warnSrc;
import com.sun.mail.imap.IMAPMessage;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.util.MimeMessageParser;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.activation.DataSource;
import javax.ejb.Stateless;
import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2016/9/5.
 */
@Stateless
public class emailDAOImpl extends AccessDB implements emailDAO {
    @Override
    public ResultDTO addsendinfo(emailsendPullDTO emailsend) {

        String senid = emailsend.getSendId();
        if (senid != null && !senid.equals("")) {

            String sql = "select count(1) from emial_sendinfo where sendId='" + senid + "'";

            String existName = getReportingToOne(sql);

            if (!existName.equals("0")) {
                return updateEmailsendInfo(emailsend);
            }
        }


        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        int resultls = 0;

        String existName = "";

        //构建返回对象
        ResultDTO resultDTO = new ResultDTO();
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        String tonames = "";
        if (emailsend.getZhusonglist() != null && emailsend.getZhusonglist().size() > 0) {
            for (int i = 0; i < emailsend.getZhusonglist().size(); i++) {
                send_email_item s = emailsend.getZhusonglist().get(i);
                String name = s.getText();
                String emailnumber = s.getId();
                tonames += name;
            }
        }
        String copynames = "";
        if (emailsend.getCopylist() != null && emailsend.getCopylist().size() > 0) {
            for (int i = 0; i < emailsend.getCopylist().size(); i++) {
                send_email_item s = emailsend.getCopylist().get(i);
                String name = s.getText();
                String emailnumber = s.getId();
                copynames += name;
            }
        }
        String email_insert = "";
        email_insert += "insert into emial_sendinfo (sendId,filepath,filepath_absolut,file_type,to_user,copy_user,title," +
                "msg,send_time,member_id,type) " +
                "values ('" + uuid + "','" + emailsend.getFile_url() + "','" + emailsend.getFilepath_absolut() + "'" +
                ",'" + emailsend.getFile_type() + "','" + tonames + "','" + copynames + "','" + emailsend.getTitle() + "'" +
                ",'" + emailsend.getMsg() + "','" + time + "','" + emailsend.getMember_id() + "','" + emailsend.getType() + "')";
        //插入业务表
        resultls = addReportingTo(email_insert);

        if (resultls != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }
        return resultDTO;
    }

    /**
     * 保存图片方法
     *
     * @param
     * @return
     */
    public String[] getFile(emailsendPullDTO emailsend) {
        String str[] = new String[3];

        ResultDTO resultDTO = new ResultDTO();
        // TODO Auto-generated method stub
        String enpenform_image = "";
        //获取配置图片地址
        String[] image_path = this.getImage_path();
        String image_pathAddr = image_path[1];//服务器项目目录地址
        String image_pathSerAddr = image_path[2];//图片访问地址
        String imgDirct = image_pathAddr + "/notice";
        File f = new File(imgDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String imgPath = imgDirct + "/" + emailsend.getFile_type();


        //base64字符串保存为图片
        boolean headImg = FileProcess.GenerateImage(emailsend.getFilestream(), imgPath);
        FileProcess.newlog("执行头像图片储存方法，储存照片地址：" + imgPath + " 方法返回：" + headImg);
        int resultls = 0;
        int mresult = 0;

        String imgurl = image_pathSerAddr + "/notice/" + emailsend.getFile_type();

        //ArrayList<HeadPortaitDTO> result = new ArrayList<HeadPortaitDTO>();

        if (headImg) {
            //插入头像表
            enpenform_image += "insert into attachment(attachment_id,attachment_addr,head_portrait_time,file_type,file_name) values ('" + uuid + "','" + imgurl + "','" + df.format(new Date()) + "','" + emailsend.getFile_type() + "','" + emailsend.getFile_name() + "')";
            // enpenform_image += "insert into file(file_id,file_addr,file_time,filegui_id,file_name) values ('" + uuid + "','" +imgurl+ "','" +df.format(new Date()) + "','" + dataDTO.getFilegui_id() + "','" + dataDTO.getFiletype() + "')";
        }

        //执行sql
        resultls = addReportingTo(enpenform_image);
        if (resultls != 0) {
            str[0] = uuid;
            str[1] = imgurl;
            str[2] = emailsend.getFile_type();
            str[3] = imgPath;
            return str;
        }
        return null;
    }

    /**
     * 查询
     * 全部  无参
     * 单个详情 主键id
     *
     * @param search
     * @param page
     * @param size
     * @return
     */
    @Override
    public ResultDTO getemailInfo(String search, String page, String size) {

        ResultDTO resultDTO = new ResultDTO();
        try {
            JSONObject json = new JSONObject(search);
            String existName = "0";

            String sqlexit = "select count(1) from email where 1=1 ";

            String sql_w = "";//查询条件sql组合

            String sql_page = "";//分页sql组合
            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(size);
            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok) + "," + size + "";
            }

            if (json.has("email_id")) {
                sql_w += " AND email_id = '" + json.getString("email_id") + "'";
            }
            if (json.has("member_id")) {
                sql_w += " AND member_id = '" + json.getString("member_id") + "'";
            }
            if (json.has("emial_index")) {
                sql_w += " AND emial_index = '" + json.getString("emial_index") + "'";
            }
            String sql_ok = sqlexit + sql_w;//组合好的sql语句
            existName = getReportingToOne(sql_ok);

            List<String[]> seresult = new ArrayList<String[]>();

            List<emailShowDTO> result = new ArrayList<emailShowDTO>();
            if (!existName.equals("0")) {
                String sql = "select email_id,email_send_url,email_copy_url,email_revice_url,email_revicepeople," +
                        "email_title,email_htmlcontent,email_textcontent,email_revicetime,email_path,email_isread from email where 1=1  " + sql_w + "  ORDER BY email_revicetime DESC " + sql_page;
                seresult = this.getReportingTo(sql);

                //构建返回对象

                for (int i = 0; i < seresult.size(); i++) {
                    String html = "";
                    if (null != seresult.get(i)[7]) {
                        html = readFile(seresult.get(i)[7]);
                        html = html.replaceAll("null", "");
                    }
                    emailShowDTO email = new emailShowDTO();
                    email.setEmail_id(seresult.get(i)[1]);
                    email.setEmail_send_url(seresult.get(i)[2]);
                    email.setEmail_copy_url(seresult.get(i)[3]);
                    email.setEmail_revice_url(seresult.get(i)[4]);
                    email.setEmail_revicepeople(seresult.get(i)[5]);
                    email.setEmail_title(seresult.get(i)[6]);
                    email.setEmail_htmlcontent(html);
                    email.setEmail_textcontent(seresult.get(i)[8]);
                    email.setEmail_revicetime(seresult.get(i)[9]);
                    email.setEmail_path(seresult.get(i)[10]);
                    email.setEmail_isread(seresult.get(i)[11]);
                    result.add(email);
                }
            }
            if (seresult.size() != 0) {
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion("邮箱信息调用成功");
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion("邮箱信息不存在");
            }
            resultDTO.setStr(result.size() + "");
            resultDTO.setValues(result);


        } catch (JSONException e) {
            e.printStackTrace();
        }
        return resultDTO;
    }

    @Override
    public ResultDTO getemail_sedInfo(String search, String page, String size) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            JSONObject json = new JSONObject(search);
            String existName = "0";

            String sqlexit = "select count(1) from emial_sendinfo where 1=1 ";

            String sql_w = "";//查询条件sql组合

            String sql_page = "";//分页sql组合
            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(size);
            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok) + "," + size + "";
            }

//            if(json.has("isverify")){
//                sql_w += " AND isverify ='" + json.getString("isverify")+"'";
//            }else{
//                sql_w += " AND (isverify IS NULL OR isverify=0)";
//            }
            if (json.has("sendId")) {
                sql_w += " AND sendId = '" + json.getString("sendId") + "'";
            }
            if (json.has("member_id")) {
                sql_w += " AND member_id = '" + json.getString("member_id") + "'";
            }
            if (json.has("type")) {
                sql_w += " AND type = '" + json.getString("type") + "'";
            }
            String sql_ok = sqlexit + sql_w;//组合好的sql语句
            existName = getReportingToOne(sql_ok);

            List<String[]> seresult = new ArrayList<String[]>();

            List<emailsendPullDTO> result = new ArrayList<emailsendPullDTO>();
            if (!existName.equals("0")) {
                String sql = "select sendId,filepath,file_type,to_user,title,msg,send_time,member_id,copy_user,filepath_absolut from emial_sendinfo where 1=1 " + sql_w + " ORDER BY send_time DESC" + sql_page;
                seresult = this.getReportingTo(sql);

                //构建返回对象

                for (int i = 0; i < seresult.size(); i++) {

                    emailsendPullDTO email = new emailsendPullDTO();
                    email.setSendId(seresult.get(i)[1]);
                    email.setFilepath(seresult.get(i)[2]);
                    email.setFile_type(seresult.get(i)[3]);
                    email.setTo_user(seresult.get(i)[4]);
                    email.setTitle(seresult.get(i)[5]);
                    email.setMsg(seresult.get(i)[6]);
                    email.setSend_time(seresult.get(i)[7]);
                    email.setMember_id(seresult.get(i)[8]);
                    email.setTo_use(seresult.get(i)[9]);
                    email.setFilepath_absolut(seresult.get(i)[10]);
                    result.add(email);
                }
            }
            if (seresult.size() != 0) {
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion("邮箱信息调用成功");
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion("邮箱信息不存在");
            }
            resultDTO.setStr(result.size() + "");
            resultDTO.setValues(result);


        } catch (JSONException e) {
            e.printStackTrace();
        }
        return resultDTO;
    }


    /**
     * 增加邮件
     *
     * @param emailDTO
     * @return
     */
    @Override
    public ResultDTO addemailInfo(emailPullDTO emailDTO) {


        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        int resultls = 0;

        String existName = "";

        //构建返回对象
        ResultDTO resultDTO = new ResultDTO();
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String email_insert = "";
        email_insert += "insert into email (email_id,email_send_url,email_copy_url,email_revice_url,email_revicepeople," +
                "email_title,email_htmlcontent,email_textcontent,email_revicetime,email_path,member_id,emial_index,email_isread) " +
                "values ('" + uuid + "','" + emailDTO.getEmail_send_url() + "'" +
                ",'" + emailDTO.getEmail_copy_url() + "','" + emailDTO.getEmail_revice_url() + "','" + emailDTO.getEmail_revicepeople() + "'" +
                ",'" + emailDTO.getEmail_title() + "','" + emailDTO.getEmail_htmlcontent() + "','" + emailDTO.getEmail_textcontent() + "','" + emailDTO.getEmail_revicetime() + "','" + emailDTO.getEmail_path() + "','"
                + emailDTO.getMember_id() + "','" + emailDTO.getEmial_index() + "','" + emailDTO.getEmail_isread() +"')";
        //插入业务表
        resultls = addReportingTo(email_insert);

        if (resultls != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion("邮件信息添加成功");
        } else {

            resultDTO.setStatus("90001");
            resultDTO.setDescritpion("邮件信息添加失败");
        }
        return resultDTO;
    }


    /**
     * 删除邮件
     *
     * @param emailDTO
     * @return
     */
    @Override
    public ResultDTO deleteEmailInfo(emailPullDTO emailDTO) {

        String sql = "select count(1) from email where email_id = '" + emailDTO.getEmail_id() + "'";

        String existName = getReportingToOne(sql);

        int results = 0;

        ResultDTO resultDTO = new ResultDTO();

        if (existName != null) {

            String QUERY = "";

            QUERY += "delete from email where email_id = '" + emailDTO.getEmail_id() + "'";

            results = this.addReportingTo(QUERY);
        }
        if (results != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion("调用成功，删除成功");
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion("调用失败，删除失败");
        }

        return resultDTO;
    }

    @Override
    public ResultDTO updateEmailInfo(emailPullDTO emailDTO) {

        ResultDTO resultDTO = new ResultDTO();

        String QUERY = "";

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //更新sql语句
        QUERY += "update email set update_time ='" + df.format(new Date()) + "'";
        if (!"".equals(emailDTO.getEmial_index())) {
            QUERY += ",emial_index = '" + emailDTO.getEmial_index() + "'";
        }

        if(!"".equals(emailDTO.getEmail_isread())){
            QUERY += ",email_isread = '" + emailDTO.getEmail_isread() + "'";
        }

        QUERY += " where email_id = '" + emailDTO.getEmail_id() + "'";
        int result = this.addReportingTo(QUERY);

        // 判断SQl是否执行成功
        if (result != 0) {

            resultDTO.setStatus("90000");//
            resultDTO.setDescritpion(warnSrc.update_success);
        } else {
            resultDTO.setStatus("90001");//
            resultDTO.setDescritpion(warnSrc.update_fail);
        }


        return resultDTO;
    }

    @Override
    public ResultDTO deleteEmailsendInfo(emailsendPullDTO emailDTO) {
        String sql = "select count(1) from emial_sendinfo where sendId = '" + emailDTO.getSendId() + "'";

        String existName = getReportingToOne(sql);

        int results = 0;

        ResultDTO resultDTO = new ResultDTO();

        if (existName != null) {

            String QUERY = "";

            QUERY += "delete from emial_sendinfo where sendId = '" + emailDTO.getSendId() + "'";

            results = this.addReportingTo(QUERY);
        }
        if (results != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion("调用成功，删除成功");
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion("调用失败，删除失败");
        }

        return resultDTO;
    }

    @Override
    public ResultDTO updateEmailsendInfo(emailsendPullDTO emailDTO) {
        String sql_isHas = "select count(1) from emial_sendinfo WHERE sendId='" + emailDTO.getSendId() + "'";

        String existMeetingRoom = getReportingToOne(sql_isHas);

        int resultls = 0;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        //构建返回对象
        ResultDTO resultDTO = new ResultDTO();
        if (!existMeetingRoom.equals("0")) {
            String update = "";
            update += "update emial_sendinfo set  update_time='" + time + "'";

            if (null != emailDTO.getTo_user() && !"".equals(emailDTO.getTo_user())) {
                update += ",to_user='" + emailDTO.getTo_user() + "'";
            }
            if (null != emailDTO.getTo_use() && !"".equals(emailDTO.getTo_use())) {
                update += ",copy_user='" + emailDTO.getTo_use() + "'";
            }
            if (null != emailDTO.getTitle() && !"".equals(emailDTO.getTitle())) {
                update += ",title='" + emailDTO.getTitle() + "'";
            }
            if (null != emailDTO.getMsg() && !"".equals(emailDTO.getMsg())) {
                update += ",msg='" + emailDTO.getMsg() + "'";
            }
            if (null != emailDTO.getType() && !"".equals(emailDTO.getType())) {
                update += ",type='" + emailDTO.getType() + "'";
            }

            update += " where sendId='" + emailDTO.getSendId() + "'";
            //更新会议室表
            resultls = addReportingTo(update);
        }

        if (resultls != 0) {
            resultDTO.setStr(emailDTO.getSendId());
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.update_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.update_fail);
        }
        return resultDTO;
    }

    @Override
    public ResultDTO sendEmail(emailsendPullDTO emailsend) {

        if (emailsend.getType().equals("2")) {
            if (emailsend.getFilestream() != null && emailsend.getFilestream() != "") {
                String fileurl = getFile(emailsend)[1];
                String filename = getFile(emailsend)[2];
                String filepathabsolut = getFile(emailsend)[3];
                emailsend.setFile_url(fileurl);
                emailsend.setFile_type(filename);
                emailsend.setFilepath_absolut(filepathabsolut);
            }

            return addsendinfo(emailsend);
        }
        ResultDTO resultDTO = new ResultDTO();
        String result = "";
        try {


            MailInfo info = new MailInfo();
            List<String> receiver = new ArrayList<String>();
            if (emailsend.getZhusonglist() != null && emailsend.getZhusonglist().size() > 0) {

                for (int i = 0; i < emailsend.getZhusonglist().size(); i++) {
                    String address = emailsend.getZhusonglist().get(i).getId();
                    receiver.add(address);
                }

            }
            List<String> copyto = new ArrayList<String>();
            if (emailsend.getCopylist() != null && emailsend.getCopylist().size() > 0) {
                for (int i = 0; i < emailsend.getCopylist().size(); i++) {
                    String replyAddress = emailsend.getCopylist().get(i).getId();
                    copyto.add(replyAddress);
                }
            }
            info.setToAddress(receiver);
            info.setReplayAddress(copyto);

            info.setSubject(emailsend.getTitle());
            info.setContent(emailsend.getMsg());

            if(emailsend.getMember_email().contains("163.com")){
                info.setHost("smtp.163.com");
            }
            if(emailsend.getMember_email().contains("qq.com")){
                info.setHost("smtp.qq.com");
            }
            if(emailsend.getMember_email().contains("sina.com")){
                info.setHost("smtp.sina.com");
            }
            if(emailsend.getMember_email().contains("126.com")){
                info.setHost("smtp.126.com");
            }

            info.setFormName(emailsend.getMember_email());
            info.setFormPassword(emailsend.getMember_email_psw());
            info.setUserName(emailsend.getFrom_username());

            EmailAttachment attachment = new EmailAttachment();

            if (emailsend.getFilestream() != null && emailsend.getFilestream() != "") {
                String file[] = getimage(emailsend);
                String fileurl = file[0];
                attachment.setPath(fileurl);
                emailsend.setFile_url(file[1]);
                emailsend.setFilepath_absolut(fileurl);
                attachment.setDisposition(EmailAttachment.ATTACHMENT);
                attachment.setDescription(emailsend.getFile_description());
                attachment.setName(emailsend.getFile_name());
//                email.attach(attachment);
                // Create the attachment
                File fileAttech = new File(fileurl);
                info.setAttechment(fileAttech);
            }

            try {
                MailSendUtil.sendHtmlMail(info);
                result = "1";
            } catch (Exception e) {
                System.out.print("'" + emailsend.getTitle() + "'的邮件发送失败！");
                result = "";
                e.printStackTrace();
            }

        } catch (Exception e) {
            System.out.print(e.getMessage());
            // return "";
            //  e.printStackTrace();
        }

        if (!result.equals("")) {
            addsendinfo(emailsend);
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion("邮件发送成功");
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion("邮件发送失败");
        }
        return resultDTO;
    }

//    @Override
//    public ResultDTO receiverEmail(String search) {
////        MessageParser.parse(SimpleMailReceiver.fetchInbox(HostType.NETEASE.getProperties(),
////                AuthenticatorGenerator.getAuthenticator("18329931971", "wlb123321")));
//
//        JSONObject json;
//        String member_id = "", member_email = "", member_email_psw = "";
//        try {
//            json = new JSONObject(search);
//            if (json.has("member_id")) {
//                member_id = json.getString("member_id");
//            }
//            if (json.has("member_email")) {
//                member_email = json.getString("member_email");
//            }
//            if (json.has("member_email_psw")) {
//                member_email_psw = json.getString("member_email_psw");
//            }
//
//
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//
////        String sql = "select * from email";
////        String existName = getReportingToOne(sql);
//        int results = 0;
//
//        ResultDTO resultDTO = new ResultDTO();
//
////        if (existName != null) {
////
////            String QUERY = "";
////
////            QUERY += "delete from email where member_id='" + member_id + "'";
////
////            results = this.addReportingTo(QUERY);
////        }
//        int r = -1;
//        //if (results != 0) {
//
//        r = parse(member_id, SimpleMailReceiver.fetchInbox(HostType.NETEASE.getProperties(),
//                AuthenticatorGenerator.getAuthenticator(member_email, member_email_psw)));
//
//        //}
//
//        if (r == 1) {
//            resultDTO.setStatus("90000");//
//            resultDTO.setDescritpion("邮箱获取成功！");
//        } else {
//            resultDTO.setStatus("90001");
//            resultDTO.setDescritpion("邮箱获取失败！");
//        }
//        return resultDTO;
//    }


    @Override
    public ResultDTO receiverEmail(String search) {

        JSONObject json;
        String member_id = "", member_email = "", member_email_psw = "";
        try {
            json = new JSONObject(search);
            if (json.has("member_id")) {
                member_id = json.getString("member_id");
            }
            if (json.has("member_email")) {
                member_email = json.getString("member_email");
            }
            if (json.has("member_email_psw")) {
                member_email_psw = json.getString("member_email_psw");
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }

        int results = 0;

        ResultDTO resultDTO = new ResultDTO();
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imap");
        if(member_email.contains("@163.com")){
            props.setProperty("mail.imap.host", "imap.163.com");
        }
        if(member_email.contains("@qq.com")){
            props.setProperty("mail.imap.host", "imap.qq.com");
        }
        if(member_email.contains("@sina.com")){
            props.setProperty("mail.imap.host", "imap.sina.com");
        }
        if(member_email.contains("@126.com")){
            props.setProperty("mail.imap.host", "imap.126.com");
        }


        // 创建Session实例对象
        Session session = Session.getInstance(props);
        Store store = null;
        try {
            store = session.getStore("imap");

            store.connect(member_email, member_email_psw);

            // 获得收件箱
            Folder folder = store.getFolder("INBOX");
        /* Folder.READ_ONLY：只读权限
         * Folder.READ_WRITE：可读可写（可以修改邮件的状态）
         */
            folder.open(Folder.READ_WRITE); //打开收件箱

            // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数
            System.out.println("未读邮件数: " + folder.getUnreadMessageCount());

            // 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0
            System.out.println("删除邮件数: " + folder.getDeletedMessageCount());
            System.out.println("新邮件: " + folder.getNewMessageCount());

            // 获得收件箱中的邮件总数
            System.out.println("邮件总数: " + folder.getMessageCount());

            // 得到收件箱中的所有邮件,并解析
            Message[] messages = folder.getMessages();
            if (messages != null && messages.length > 0) {
                for (int i = 0, count = messages.length; i < count; i++) {
                    Message message = messages[i];
                    IMAPMessage msg = (IMAPMessage) message;
                    Flags flags = message.getFlags();
                    if(!flags.contains(Flags.Flag.SEEN)){
                        System.out.println("------------------解析第" + message.getMessageNumber() + "封邮件-------------------- ");
                        parse(message, member_id);
                        System.out.println("------------------第" + message.getMessageNumber() + "封邮件解析结束-------------------- ");
                        msg.setFlags(flags,true);
                    }
                }
            }
            if (messages == null || messages.length < 1) {
                resultDTO.setStatus("90001");//
                resultDTO.setDescritpion("未收到邮件！");
            } else {
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion("邮件收取成功！");
            }
            //释放资源
            folder.close(true);
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


        return resultDTO;
    }

    /**
     * 邮件附件存放位置
     */
//    public String folder = "D:\\upload";
    public void parse(Message message, String member_id) {
        String fileName = "";
        String imgurl = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        try {
            MimeMessage msg = (MimeMessage) message;
            String from = POP3ReceiveMailTest.getFrom(msg);
            String cc = POP3ReceiveMailTest.getReceiveAddress(msg, null);

            MimeMessageParser parser = new MimeMessageParser((MimeMessage) message).parse();
//            String from = parser.getFrom(); // 获取发件人地址
//            List<Address> cc = parser.getCc();// 获取抄送人地址
            List<Address> to = parser.getTo(); // 获取收件人地址
            String replyTo = parser.getReplyTo();// 获取回复邮件时的收件人
            String subject = parser.getSubject(); // 获取邮件主题
            String htmlContent = parser.getHtmlContent(); // 获取Html内容
            String plainContent = parser.getPlainContent(); // 获取纯文本邮件内容（注：有些邮件不支持html）

            System.out.println("邮件主题：---" + subject + "来自--" + replyTo);

            List<DataSource> attachments = parser.getAttachmentList(); // 获取附件，并写入磁盘
            for (DataSource ds : attachments) {
                BufferedOutputStream outStream = null;
                BufferedInputStream ins = null;
                try {
//                    fileName = folder + File.separator + ds.getName();
                    String[] image_path = this.getImage_path();
                    String image_pathAddr = image_path[1];//服务器项目目录地址
                    String image_pathSerAddr = image_path[2];//图片访问地址
                    String imgDirct = image_pathAddr + "/email";
                    File f = new File(imgDirct);
                    if (!f.exists()) {
                        f.mkdirs();
                        f.setWritable(true, false);
                    }
                    fileName = imgDirct + "/" + ds.getName();
                    outStream = new BufferedOutputStream(new FileOutputStream(fileName));
                    ins = new BufferedInputStream(ds.getInputStream());
                    byte[] data = new byte[2048];
                    int length = -1;
                    while ((length = ins.read(data)) != -1) {
                        outStream.write(data, 0, length);
                    }
                    outStream.flush();

                    imgurl = "/email" + "/" + ds.getName();
                    System.out.println("附件:" + fileName);
                } finally {
                    if (ins != null) {
                        ins.close();
                    }
                    if (outStream != null) {
                        outStream.close();
                    }
                }

            }


            emailPullDTO email = new emailPullDTO();
            email.setEmial_index(0);
            email.setEmail_send_url(from);
            email.setEmail_copy_url(cc.toString());
            email.setEmail_revice_url(cc.toString());
            email.setEmail_revicepeople(replyTo);
            email.setEmail_title(subject);
            if (htmlContent != null && !htmlContent.equals("")) {
                // String html = htmlContent.replaceAll("\'", "\" ");
                // html = htmlContent.replaceAll("Xi\'an", "Xian");
                String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
                String attachsddress = saveFile(htmlContent, uuid);
                email.setEmail_htmlcontent(attachsddress);
            } else {
                email.setEmail_htmlcontent("");
            }
//            else {
//                email.setEmail_htmlcontent(plainContent);
//            }
            email.setEmail_textcontent(plainContent == null? "" : plainContent);
            email.setEmail_revicetime(df.format(message.getSentDate()));
            email.setEmail_path(imgurl);
            email.setMember_id(member_id);
            email.setEmail_isread("0");

            String sql = "select count(1) from email where email_revicetime='" + email.getEmail_revicetime() + "'";

            String exist = getReportingToOne(sql);
            if (exist.equals("0")) {
                addemailInfo(email);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String saveFile(String html, String id) {
        String imgurl = "";
        String[] image_path = this.getImage_path();
        String image_pathAddr = image_path[1];//服务器项目目录地址
        String image_pathSerAddr = image_path[2];//图片访问地址

        String imgDirct = image_pathAddr + "/email";
        File f = new File(imgDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        String imgPath = imgDirct + "/" + id + ".txt";
        File file = new File(imgPath);
        try {
            file.createNewFile();
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            out.write(html); // \r\n即为换行
            out.flush(); // 把缓存区内容压入文件
            out.close(); // 最后记得关闭文件
            imgurl = image_pathSerAddr + "/email" + "/" + id + ".txt";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgPath;
    }

    public String readFile(String path) {
        String result = null;
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        try {
            fileReader = new FileReader(path);
            bufferedReader = new BufferedReader(fileReader);
            try {
                String read = null;
                while ((read = bufferedReader.readLine()) != null) {
                    result = result + read + "\r\n";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//        System.out.println("读取出来的文件内容是："+"\r\n"+result);
        return result;
    }


    public int parse(String member_id, Message... messages) {
        int falg = -1;
        if (messages == null || messages.length == 0) {
            System.out.println("没有任何邮件");
        } else {
            //删除所有
            falg = 1;
            for (Message m : messages) {
                parse(m, member_id);
            }
            // 最后关闭连接
            if (messages[0] != null) {
                Folder folder = messages[0].getFolder();
                if (folder != null) {
                    try {
                        Store store = folder.getStore();
                        folder.close(false);// 参数false表示对邮件的修改不传送到服务器上
                        if (store != null) {
                            store.close();
                        }
                    } catch (MessagingException e) {
                        // ignore
                    }
                }
                //
            }
        }
        return falg;
    }


    public String[] getimage(emailsendPullDTO emailsend) {
        String url[] = new String[2];

        String enpenform_image = "";
        //获取配置图片地址
        String[] image_path = this.getImage_path();
        String image_pathAddr = image_path[1];//服务器项目目录地址
        String image_pathSerAddr = image_path[2];//图片访问地址


        String imgDirct = image_pathAddr + "/email";
        File f = new File(imgDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String imgPath = imgDirct + "/" + emailsend.getFile_type();


        //base64字符串保存为图片
        boolean headImg = FileProcess.GenerateImage(emailsend.getFilestream(), imgPath);
        FileProcess.newlog("执行头像图片储存方法，储存照片地址：" + imgPath + " 方法返回：" + headImg);
        int resultls = 0;
        int mresult = 0;

        String imgurl = "/email" + "/" + emailsend.getFile_type();
        url[0] = imgPath;
        url[1] = imgurl;
        return url;
    }

}
